﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.Practices.Unity;
using Vit.Common;
using Vit.Common.Extensions;
using Vit.Web.Providers;

namespace Vit.Web.HttpModule
{
    public class UrlRewriteModule : IHttpModule
    {
        public string[] IgnoredFiles = new string[] { ".axd", ".ico" };
        public string[] IgnoredFolders = new string[] { "/skins/", "/scripts/" };

        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication application = sender as HttpApplication;
            if (application.Context.Request.RequestType == "POST")
                return;
            string lowerPath = application.Context.Request.Path.ToLower();
            if (IgnoredFiles.Any(o => lowerPath.EndsWith(o)))
                return;
            if (IgnoredFolders.Any(o => lowerPath.IndexOf(o) >= 0))
                return;

            string rawUrl = application.Request.Url.PathAndQuery;
            string mapUrl = Unity.Current.Resolve<IFriendlyUrlProvider>().RewriteUrl(rawUrl);
            if (!string.IsNullOrWhiteSpace(mapUrl) && rawUrl.Equals(mapUrl, StringComparison.OrdinalIgnoreCase) == false)
                application.Context.RewritePath(mapUrl, false);
        }

        #endregion
    }
}
